package com.jlf.starter.mp;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.baomidou.mybatisplus.core.metadata.MyTableInfo;
import com.baomidou.mybatisplus.core.metadata.MyTableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.jlf.core.annotation.Domain;
import com.jlf.core.annotation.DomainRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.MapperBuilderAssistant;

import java.util.List;
import java.util.Set;

/**
 * 领域的默认sql注入
 *
 * @author wujr
 * 2021/9/28
 * @version 1.0
 * 变更历史
 * [wujr 2021/9/28 1.0 新增]
 */
@Slf4j
public class DomainDefaultSqlInjector extends DefaultSqlInjector {
    @Override
    public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
        Class<?> modelClass = ReflectionKit.getSuperClassGenericType(mapperClass, Mapper.class, 0);
        if (modelClass != null) {
            String className = mapperClass.toString();
            Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
            if (!mapperRegistryCache.contains(className)) {
                MyTableInfo tableInfo = MyTableInfoHelper.initTableInfo(builderAssistant, modelClass);
                List<AbstractMethod> methodList = this.getMethodList(mapperClass, tableInfo);
                if (CollectionUtils.isNotEmpty(methodList)) {
                    Domain annotation = tableInfo.getAnnotation();
                    String domainName = tableInfo.getDomainName();
                    DomainRepository.add(mapperClass, domainName);
                    DomainRepository.add(modelClass, annotation);
                    // 循环注入自定义方法
                    methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));
                } else {
                    log.debug(mapperClass + ", No effective injection method was found.");
                }
                mapperRegistryCache.add(className);
            }
        }
    }
}
